import { reactive, ref, unref, watch, type Ref } from 'vue'
import { defineStore } from 'pinia'
import { Sysinfo } from '@/common/config'
import { CURRENT_ROUTE_INFO_KEY, JWT_TOKEN_KEY, ROUTER_NAV_LIST_KEY } from '@/constants'
import ssHelper from '@/common/sessionStoreHelper'

export const useRequester = defineStore('requester', () => {
  const isHttpEncrypt = ref(false)
  const shareKey = ref('')

  return { isHttpEncrypt, shareKey }
})

export type RouteInfoType = {
  currentRoute: string
  navArray: Array<any>
}

export const useUsers = defineStore('users', () => {
  // 登录账号的name、username
  const userName = ref(ssHelper.get('userName'))
  // 登录者的唯一编码--更换密码时会使用
  const userUid = ref(ssHelper.get('userUid'))
  // 执行流程时对应的变量为 $_login_id
  const nameId = ref(ssHelper.get('nameId'))
  // 用户类型(R999为超级管理员)
  const userType = ref(ssHelper.get('userType'))
  // 用户编号
  const userNo = ref(ssHelper.get('userNo'))
  // 用户图片
  const avatar = ref(ssHelper.get('avatar'))
  // 用户的角色编号（职位编号）---字符串类型，一个账号可能会有多个角色，多个角色采用 , 分隔
  const roleNo = ref(ssHelper.get('roleNo'))
  // 用户的角色（职位）---字符串类型，一个账号可能会有多个角色，多个角色采用 , 分隔
  const roleName = ref(ssHelper.get('rolename'))
  const hadRequestError = ref(0)
  // 当前用户登录菜单
  const routerNavList: Ref<Array<any>> = ref(ssHelper.get(ROUTER_NAV_LIST_KEY, []))
  // 当前跳转路由信息
  const currentRouteInfo: Ref<RouteInfoType> = ref(
    ssHelper.get(CURRENT_ROUTE_INFO_KEY, {
      currentRoute: '',
      navArray: []
    })
  )
  const siteId = ref(ssHelper.get('siteId'))
  // 授权token
  const token = ref(ssHelper.get(JWT_TOKEN_KEY))

  const setLoginInfo = (info: {
    loginUID: string
    userName: string
    userUid: string
    nameId: string
    userType: string
    userNo: string
    avatar: string
    roleNo: string
    roleName: string
    mobile?: string
    siteId: string
  }) => {
    userName.value = info.userName
    userUid.value = info.userUid
    nameId.value = info.nameId
    userType.value = info.userType
    userNo.value = info.userNo
    avatar.value = info.avatar
    roleNo.value = info.roleNo
    roleName.value = info.roleName
    siteId.value = info.siteId

    ssHelper.set('userUid', info.loginUID)
    // 用户类型(R999为超级管理员)
    ssHelper.set('userType', info.userType)
    // 用户编号
    ssHelper.set('userNo', info.userNo)
    // 登录者的角色(职位)编号，多个角色已逗号分隔，GM--经理
    ssHelper.set('roleNo', info.roleNo)
    // 执行流程时对应的变量为 $_login_id
    ssHelper.set('nameId', info.nameId)
    // 用户图片
    ssHelper.set('avatar', info.avatar)
    ssHelper.set('userName', info.userName)
    ssHelper.set('rolename', info.roleName)
    ssHelper.set('siteId', info.siteId)
  }
  const getLoginToken = () => token.value
  const setLoginToken = (v: string) => {
    token.value = v
    ssHelper.set(JWT_TOKEN_KEY, v)
  }
  function logout() {
    ssHelper.clear()
    userName.value = ''
    userUid.value = ''
    nameId.value = ''
    userType.value = ''
    userNo.value = ''
    roleNo.value = ''
    roleName.value = ''
    avatar.value = ''
    siteId.value = ''
    hadRequestError.value = 0
    routerNavList.value = []
  }
  const setCurrentRouteInfo = (r: RouteInfoType) => {
    currentRouteInfo.value = r
    ssHelper.set(CURRENT_ROUTE_INFO_KEY, r)
  }
  const getCurrentRouteInfo = () => unref(currentRouteInfo)
  const setRouterNavList = (v: Array<any>) => {
    routerNavList.value = v
    ssHelper.set(ROUTER_NAV_LIST_KEY, v)
  }
  const getRouterNavList = () => unref(routerNavList)

  return {
    userName,
    userUid,
    nameId,
    userType,
    userNo,
    avatar,
    roleNo,
    roleName,
    siteId,
    hadRequestError,
    logout,
    setLoginInfo,
    setLoginToken,
    getLoginToken,
    setCurrentRouteInfo,
    getCurrentRouteInfo,
    setRouterNavList,
    getRouterNavList,
    routerNavList
  }
})

export const useAppSettings = defineStore('appsettings', () => {
  // 是否初次运行
  const isFirstRun = ref(false)
  // 全局样式定义

  const theme = ssHelper.get('theme', {})
  const themeSettings: { [key: string]: any } = reactive({
    color: theme.color ? theme.color : '',
    layout: theme.layout ? theme.layout : '',
    collapseMenu: theme.collapseMenu ? theme.collapseMenu : false,
    showNotice: Sysinfo.ShowNotice ? Sysinfo.ShowNotice : true
  })
  const changeThemeColor = (theme: string) => {
    themeSettings.color = theme
    ssHelper.set('theme', themeSettings)
  }
  const getThemeColor = (): string => {
    return themeSettings.color
  }
  const setCollapseMenu = (v: boolean) => {
    themeSettings.collapseMenu = v
    ssHelper.set('theme', themeSettings)
  }
  const isCollapseMenu = (): boolean => themeSettings.collapseMenu

  const showNotice = (): boolean => themeSettings.showNotice
  const setShowNotice = (v: boolean) => {
    themeSettings.showNotice = v
    ssHelper.set('theme', themeSettings)
  }

  return {
    isFirstRun,
    isCollapseMenu,
    setCollapseMenu,
    getThemeColor,
    changeThemeColor,
    showNotice,
    setShowNotice
  }
})

export const useLocale = defineStore('locale', () => {
  //系统默认中文
  const defaultLang = 'zh-cn'
  const curLocale = ref(defaultLang)
  let localeMap: { [key: string]: any } = reactive({})

  const setCurrentLocale = async (locale: string) => {
    if (!locale) locale = defaultLang
    curLocale.value = locale
    const localemodule = await import(`../../src/locales/${locale}.ts`).catch((err) => {
      console.error(err)
    })
    if (localemodule) {
      localeMap = reactive(localemodule.default)
    }
  }

  const t = (key: string) => {
    if (curLocale.value === defaultLang) {
      return key
    } else {
      if (localeMap && localeMap[key]) {
        return localeMap[key]
      } else {
        return key
      }
    }
  }

  return { curLocale, setCurrentLocale, t }
})
